﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

using ICSharpCode.AvalonEdit;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

using Xc.DataAccess.Core;
using Xc.DataAccess.Core.Services;
using Xc.Views.Core;

namespace Xc.Views.Booster.Services
{
    /// <summary>
    /// APP配置服务
    /// </summary>
    /// <typeparam name="TAppSetting"></typeparam>
    public class AppSettingService<TAppSetting> : IAppSettingService where TAppSetting : class
    {
        private readonly IServiceProvider options;
        private readonly IConverterService converterService;
        private readonly IApplicationBooster<TAppSetting> startUp;
        /// <summary>
        /// APP配置服务
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <param name="converterService"></param>
        /// <param name="startUp"></param>
        public AppSettingService(IServiceProvider serviceProvider, IConverterService converterService, IApplicationBooster<TAppSetting> startUp)
        {
            this.options = serviceProvider;
            this.converterService = converterService;
            this.startUp = startUp;
        }
        /// <summary>
        /// 获取APP配置信息
        /// </summary>
        /// <returns></returns>
        public string GetAppSetting()
        {
            var d = options.CreateScope().ServiceProvider.GetService<IOptionsSnapshot<TAppSetting>>();
            var text = converterService.ToJsonString(d.Value);
            return text;
        }
        /// <summary>
        /// 保存配置信息
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public Result SetAppSetting(string content)
        {
            var text = converterService.FromJsonString<TAppSetting>(content);
            if (text != null)
            {
                var res = startUp.UpdateAppSettingFile(text);
                if (res.IsSuccess)
                {
                    return Result.Accept(res.Message);
                }
                else
                {
                    return Result.Reject(res.Message);
                }
            }
            else
            {
                return Result.Reject("格式错误，保存失败");
            }
        }
    }
}
